<template>
    <div class="addglobal">

        <div class="leftbjq">

            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                :mode="mode" />
            <Editor :style="{ height: height + 'px', 'overflow-y': 'hidden' }" v-model="valueHtml"
                :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" @onChange="onChange" />
        </div>
        <div class="rightitem">
            <div class="title">设置</div>
            <el-form :model="form" ref="articleform" label-width="auto" :rules="rules" style="max-width: 600px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入标题" />
                </el-form-item>
                <el-form-item label="板块" required>
                    <el-cascader v-model="boardids" :options="options" @change="changebk" :props="props1" placeholder="请选择" clearable />

                </el-form-item>
                <el-form-item label="封面" prop="cover">
                    <el-upload name="file" :show-file-list="false"
                        accept=".png,.PNG,.jpg,.JpG,.jpeg,.JPEG,gif,.GIF,.bmp,.BMP" :multiple="false"
                        :http-request="selectImg">
                        <img :src="commentImage" v-if="commentImage !== ''" style="width: 100px;height: 100px;" alt="">
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>


                    </el-upload>
                </el-form-item>
                <el-form-item label="摘要" prop="summary">
                    <el-input v-model="form.summary" type="textarea" placeholder="请输入摘要" />
                </el-form-item>
                <!-- <el-form-item label="附件" prop="attachment">
                    <el-upload name="file" accept=".zip" :multiple="false" :http-request="selectfile">

                        <el-button type="primary">上传</el-button>

                    </el-upload>
                </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="submit">发表</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script setup>

import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { onBeforeMount, getCurrentInstance, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue';
import service from '../utils/request';
import router from '../router';
import { useRoute } from 'vue-router';
// // import "@wangeditor/editor/dist/css/style.css";
// import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const route = useRoute();
onMounted(() => {
    console.log(route)
    if (route.query) {
        getdetail(route.query.id)
    }
    getboard()
})
const boardids=ref([])
const valueHtml=ref();
const { proxy } = getCurrentInstance();
const form = ref({});
const options = ref([]);
const commentImage = ref("");
const props1 = {
    label: "boardName",
    value: "boardId",
    checkStrictly: true,

}
const editorRef = shallowRef();
const toolbarConfig = {
    // 排除菜单组，写菜单组的key的值即可
    excludeKeys: ["uploadVideo"],
};

const editorConfig = {
    placeholder: "请输入内容",
    excludeKeys: ["uploadVideo"],
    MENU_CONF: {
        uploadImage: {
            maxFileSize: 3 * 1024 * 1024,
            server: "/api/file/upload",
            fieldName: "file",
            customInsert(responseData, insertFn) {
                // 正常请求
                if (responseData == 200) {
                    insertFn(proxy.globalInfo.imageUrl + responseData.data.fileName),
                        "",
                        "";
                    return;
                } else if (responseData == 901) {
                    // 登陆超时
                    store.commit("showLogin", true);
                    store.commit("updateLoginUserInfo", null);
                    return;
                }
                proxy.Message.error(responseData.info);
            },
        },
    },
};
const changebk = (e) => {
    console.log(e)
    if (e.length > 1) {
        form.value.pboardId = e[0]
        form.value.pBoardId = e[0]
        form.value.boardId = e[1]
    } else if (e.length == 1) {

        form.value.pboardId = e[0]
        form.value.pBoardId = e[0]
        form.value.boardId = ""

    }

}
const getdetail = async (id) => {
    const res = await service.get("/forum/ArticleDetail", {
        params: {
            articleId: id
        }
    })
    console.log(res)
    form.value=res.data.forumArticleVo
    form.value.pboardId=form.value.pBoardId;

    boardids.value.push(Number(form.value.pBoardId))
    if(form.value.boardId!=null){
        boardids.value.push(form.value.boardId)

    }
    commentImage.value= '/api/file/getImage/'+form.value.cover
    valueHtml.value=form.value.content
 console.log(valueHtml.value)
    // String title,
    //                           Integer boardId,
    //                           Integer pboardId,
    //                           MultipartFile cover,
    //                           String articleId,
    //                           MultipartFile attachment,
    //                           String summary, Integer editorType, String content, String markdownContent,Integer attachmentType
}
const submit = async () => {
     form.value.attachment = ""
    form.value.editorType = 0
 
    
    let res = await proxy.Request({
        url: form.value.articleId ? "/forum/updateArticle": "/forum/postArticle",
        params: form.value
    });
    console.log(res)
    router.push({
        path: "/detail/" + res.data
    })
    // router.go(-1)
}


onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return;
    editor.destroy()
})
const handleCreated = (editor) => {
    editorRef.value = editor//记录editor实例,重要
}
const onChange = (e) => {
    console.log(e.getHtml())
    form.value.content = e.getHtml()

}
const getboard = async () => {
    const res = await service.get("/board/loadBoard");

    // .Request({
    //   url: "/board/loadBoard"
    // })
    options.value = res.data


    console.log(res)
}
const selectfile = (file) => {
    form.value.attachment = file.file
}
const selectImg = (file) => {
    console.log(file)
    file = file.file;
    let img = new FileReader();

    img.readAsDataURL(file);
    console.log(file)

    img.onload = ({ target }) => {
        let imgData = target.result;
        commentImage.value = imgData;
        form.value.cover = file;
    };

}
const rules = {
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },

    ],


}
</script>
<style scoped>
.addglobal {
    width: 100%;
    height: auto;
    display: flex;
    justify-content: space-between;
    background: #e8e8e8;
    padding: 10px;
    box-sizing: border-box
}

.leftbjq {
    width: 79%;
    background: #fff;
}

.rightitem {
    width: 20%;
    background: #fff;
}

.title {
    font-size: 20px;
    color: #000;
    border-bottom: 1px solid #ccc;
    height: 40px;
    padding-left: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
    line-height: 40px;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    border: 1px dashed #8c939d;
}
</style>